import webview
import win32gui
import win32con
from threading import Thread
import time
import json
import os
import pystray
from PIL import Image
from pystray import MenuItem
import win32com.client
import pyautogui


def read_jsonFile(file):
    with open(file,"r")as f:
        return json.load(f)
def write_jsonFile(file,data):
    with open(file,"w")as f:
        json.dump(data,f)
        
now_playing = None

def judgeprocess(processname):
    WMI = win32com.client.GetObject('winmgmts:')
    processCodeCov = WMI.ExecQuery('select * from Win32_Process where Name="%s"' % processname)
    if len(processCodeCov) > 0:
        return True
    else:
        return False
def check_maxWindow():
    window = win32gui.GetForegroundWindow()
    if window:
        tup = win32gui.GetWindowPlacement(window)
        if tup[1] == win32con.SW_SHOWMAXIMIZED:
            return True
        else:
            return False
def gethandle():
    hwnd = win32gui.FindWindow("Progman", "Program Manager")
    a = win32gui.SendMessageTimeout(hwnd, 0x052C, 0, None, 0, 0x03E8)
    hwnd_WorkW = None
    while 1:
        hwnd_WorkW = win32gui.FindWindowEx(None, hwnd_WorkW, "WorkerW", None)
        # print("hwnd_WorkW: ",hwnd_WorkW)
        if not hwnd_WorkW:
            continue
        hView = win32gui.FindWindowEx(hwnd_WorkW, None, "SHELLDLL_DefView", None)
        # print('hwmd_hView: ', hView)
        if not hView:#这个WorkerW下没有shell
            continue
        h = win32gui.FindWindowEx(None, hwnd_WorkW, "WorkerW", None)
        while h:
            win32gui.SendMessage(h, 0x0010, 0, 0)  # WM_CLOSE
            h = win32gui.FindWindowEx(None, hwnd_WorkW, "WorkerW", None)
        break
    return hwnd
tmpHwnd = None
programName="CodeVicent-WppRunner"
def EnumWindowsProc(hwnd,lParam):
    global tmpHwnd
    className = win32gui.GetClassName(hwnd)
    if className == "WorkerW":
        SHELLDLL_DefView = win32gui.FindWindowEx(hwnd,0,"SHELLDLL_DefView",None)
        if SHELLDLL_DefView == 0:
            tmpHwnd = hwnd
    if className == "Progman":
        win32gui.SendMessage(tmpHwnd, 16, 0, 0)

# 嵌入到桌面
def embed():
    # return
    print("嵌入桌面")
    global programName
    desk = win32gui.FindWindow("Progman","Program Manager")
    background = win32gui.FindWindowEx(desk,0,"SHELLDLL_DefView",None)
    program = win32gui.FindWindow(None,programName)
    win32gui.SendMessage(desk, 0x052c, 0, 0)
    win32gui.EnumWindows(EnumWindowsProc,0)
    win32gui.SetParent(program,desk)

def open_kzt():
    if judgeprocess("Main.exe")==False:
        os.startfile("Main.exe")
def open_voice():
    pass
def close_voice():
    pass
def stop_wpp():
    try:
        os.remove("start_run.key")
    except:
        pass
    os._exit(0)
def change_char(char_id):
    try:
        os.popen("taskkill /F /IM char_runner.exe")
        now_wpp = read_jsonFile("now_wpp.json")
        now_wpp["char"]=char_id
        write_jsonFile("now_wpp.json",now_wpp)
        time.sleep(1)
        os.startfile("char_runner.exe")
    except:
        pass
def run_stray():
    menu = (
        MenuItem(text='打开空间控制台', action=open_kzt),
        MenuItem(text='停止壁纸放映', action=stop_wpp),
        )
    image = Image.open("mhkj_logo.png")
    icon = pystray.Icon("name", image, "鼠标移动到\n托盘图标上\n展示内容", menu)
    icon.run()
def check_change():
    global now_playing
    time.sleep(1)
    while True:
        with open("now_wpp.json","r")as f:
            w_data = json.load(f)
            f.close()
        if w_data["open"]==False:
            print("换为空")
            window.evaluate_js("change_href('backgroud.html')")
            now_playing=None
            time.sleep(1)
            continue
        w_data = w_data["id"]
        i_url = window.evaluate_js("document.getElementById('wpp').src")
        print(i_url)
        if w_data!=now_playing:
        # if not w_data in i_url:
            with open("wallpaper/"+w_data+"/inf.json","r")as f:
                cwppdata = json.load(f)
                f.close()
            if not (cwppdata["char_link"]=="unuse" or cwppdata["char_link"]==""):
                change_char(cwppdata["char_link"])
            if cwppdata["type"] == "only_vid":
                print("检测到壁纸切换")
                load_onlyVID_html(w_data)
                
                window.evaluate_js("change_href('./this_VIDwallpaper.html')")
                time.sleep(0.5)
                #window.evaluate_js("reload_wpp()")
                # window.evaluate_js("window.location.href=window.location.origin+'/this_VIDwallpaper.html'")
                # window.evaluate_js("location.reload()", callback=None)
            elif cwppdata["type"] == "only_html":
                print("检测到html壁纸切换")
                window.evaluate_js("change_href('/wallpaper/"+w_data+"/index.html')")
                # window.evaluate_js("change_href('/wallpaper/"+wpp_id+"/index.html')")
            now_playing=w_data
            with open("start_run.key","w")as f:
                json.dump({"time":int(time.time())},f)
                f.close()
        time.sleep(1)

def start_run():
    time.sleep(3)
    while wpp_still_run==True:
        try:
            embed()
        except Exception as e:
            print(e)
        else:
            run_everyDay(wpp_data)
            with open("wallpaper/"+wpp_id+"/inf.json","r")as f:
                wppData=json.load(f)
                f.close()
            if wppData["char_link"]!="unuse" or wppData["char_link"]!="":
                wpp_data["char"]=wppData["char_link"]
                try:
                    os.startfile("char_runner.exe")
                except:
                    pass
            if wppData["type"] == "only_html":
                window.evaluate_js("change_href('/wallpaper/"+wpp_id+"/index.html')")
                # window.evaluate_js("window.location.href=window.location.origin+'/wallpaper/"+wpp_id+"/index.html'")
            elif wppData["type"] == "only_vid":
                load_onlyVID_html(wpp_id)
                window.evaluate_js("change_href('./this_VIDwallpaper.html')")
                window.evaluate_js("reload_wpp()")
                # window.evaluate_js("window.location.href=window.location.origin+'/this_VIDwallpaper.html'")
                # window.evaluate_js("location.reload()", callback=None)
            with open("start_run.key","w")as f:
                json.dump({"time":int(time.time())},f)
                f.close()
            break
def load_onlyVID_html(wpp_id):
    with open("wallpaper/"+wpp_id+"/wpp.html","r",encoding="utf-8")as f:
        html = f.read()
        f.close()
    with open("this_VIDwallpaper.html","w",encoding="utf-8")as f:
        f.write(html)
        f.close()
ed_f = False
class API:
    def get_charData(self):
        with open("now_wpp.json","r")as f:
            wpp_data=json.load(f)
            f.close()
        char_id = wpp_data["char"]
        with open("char/"+char_id+"/char_inf.json","r")as f:
            char_data = json.load(f)
        return {"success":True,"wpp_data":char_data}
    def report_ed_ok(self):
        global ed_f
        ed_f = True
    def get_screen(self):
        screen_width, screen_height = pyautogui.size()
        return {"w":screen_width,"h":screen_height}
    def plug_readData(self,plug_id):
        return read_jsonFile("plug/"+plug_id+".json")
    def plug_dumpData(slef,plug_id,data):
        write_jsonFile("plug/"+plug_id+".json",data)
api = API()
def run_everyDay(now_wpp):
    global ed_f
    print("ed程序开启")
    if now_wpp["everyDay_open"]==True and now_wpp['everyDay_path']!="":
        print("ed已开启")
        with open("everyDay_play.txt","r",encoding="utf-8")as f:
            html = f.read()
            f.close()
        html = html.replace("!<-everyDay_path->!","./wallpaper/ed.mp4")
        with open("this_VIDwallpaper.html","w",encoding="utf-8")as f:
            f.write(html)
            f.close()
        window.evaluate_js("change_href('./this_VIDwallpaper.html')")
        window.evaluate_js("reload_wpp()")
        # window.evaluate_js("window.location.href=window.location.origin+'/this_VIDwallpaper.html'")
        # window.evaluate_js("location.reload()", callback=None)
        print("ed渲染完成")
        while True:
            if ed_f == True:
                break
            time.sleep(0.2)
    else:
        print("ed未开启，跳出")
if os.path.exists("now_wpp.json"):
    window = webview.create_window(
        'CodeVicent-WppRunner',
        'wpp_run.html',
        fullscreen=True,
        width=1600,
        height=900,
        text_select=False,
        confirm_close=True,
        js_api=api,
        transparent=True
    )
    with open("now_wpp.json","r")as f:
        wpp_data=json.load(f)
        f.close()
    wpp_id=wpp_data["id"]
    wpp_still_run = True
    thread = Thread(target=start_run)
    thread.start()
    stray_thread = Thread(target=run_stray)
    stray_thread.start()
    webview.start(check_change,http_server=True)
    wpp_still_run = False
